package com.iye.puretennis.fragment;

import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.CustomApplication;
import com.iye.puretennis.custom.CustomViewFlipper;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.domain.*;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.helper.Session;
import com.iye.puretennis.utils.TimeUtils;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Author: Chuanbao on 2014/11/19.
 */
public class MyAppointmentsFragment extends TabFragment {

    public static String TAG = "my_appointments";

    public static final int totalNum = 100;

    public static final int currentIndex = 48;

    private AvailabilitiesRequestAdapter availabilitiesRequestAdapter;

    private AppointmentsAdapter appointmentsAdapter;

    private MyGroupDropdownAdapter<MyGroup> myGroupDropdownAdapter;

    private Spinner groupsSpinner;

    private HuaWenHuPoTextView timeView;

    private List<User> users = new ArrayList<User>();

    private List<MyGroup> groups = new ArrayList<MyGroup>();

    private List<Appointment> appointments = new ArrayList<Appointment>();

    private List<Availability> availabilities = new ArrayList<Availability>();

    private String date;

    private String groupGuid;

    private String tab = "availability";

    private CustomViewFlipper viewFlipper;

    ViewElement[] viewElements = new ViewElement[2];

    View flipperView1;

    View flipperView2;


    @Override
    public void onCustomCreateView(LayoutInflater inflater) {

        groupsSpinner = (Spinner) mainView.findViewById(R.id.groups);
        groupsSpinner.getLayoutParams().width = (int) (width * 0.28);

        date = TimeUtils.today();

        timeView = (HuaWenHuPoTextView) mainView.findViewById(R.id.today_button);
        timeView.getLayoutParams().width = (int) (width * 0.5);
        timeView.setText(TimeUtils.dateLabel(date));

        viewFlipper = (CustomViewFlipper) mainView.findViewById(R.id.availabilityViewFlipper);

        flipperView1 = inflater.inflate(R.layout.flipper_view, null);

        flipperView2 = inflater.inflate(R.layout.flipper_view, null);

        viewElements[0] = new ViewElement(flipperView1, 0);

        viewElements[1] = new ViewElement(flipperView2, 1);

        viewFlipper.setMyViewFlipper(totalNum, false, currentIndex, new View[]{flipperView1, flipperView2}, loadViewData, loadViewData);


        final ImageButton addButton = (ImageButton) mainView.findViewById(R.id.add_button);

        final HuaWenHuPoTextView availabilityTab = (HuaWenHuPoTextView) mainView.findViewById(R.id.availability_tab);

        final HuaWenHuPoTextView scheduleTab = (HuaWenHuPoTextView) mainView.findViewById(R.id.schedule_tab);

        final ImageView leftArrow = (ImageView) mainView.findViewById(R.id.left_arrow);

        ImageView rightArrow = (ImageView) mainView.findViewById(R.id.right_arrow);


        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int viewId = view.getId();
                if (viewId == addButton.getId()) {
                    Session session = Session.newSession();
                    session.put("selectedUsers", users);
                    goFragment(getSourceId(), CreateAppointmentFragment.TAG, CreateAppointmentFragment.class, null, false);
                } else if (viewId == availabilityTab.getId()) {
                    tab = "availability";
                    availabilityTab.setBackgroundResource(R.drawable.tabs_item_selected_left_bg);
                    scheduleTab.setBackgroundResource(R.drawable.tabs_item_right_bg);
                    if (viewFlipper.getCurrentDataIndex() <= currentIndex) {
                        timeView.setText(TimeUtils.dateLabel(date));
                        if (viewFlipper.getIndex() == 0) {
                            date = TimeUtils.today();
                            viewFlipper.setCurrentIndex(currentIndex);
                            availabilityListRender(token, date, groupGuid, viewElements[viewFlipper.getIndex()].lv);
                            viewElements[viewFlipper.getIndex()].emptyView.setText(R.string.no_appointment);

                        } else {
                            date = TimeUtils.getDate(-1, 1, true);
                            viewFlipper.setCurrentIndex(currentIndex - 1);
                            viewFlipper.showNext();
                        }
                    } else {
                        availabilityListRender(token, date, groupGuid, viewElements[viewFlipper.getIndex()].lv);
                        viewElements[viewFlipper.getIndex()].emptyView.setText(R.string.no_appointment);
                    }
                } else if (viewId == scheduleTab.getId()) {
                    tab = "schedule";
                    availabilityTab.setBackgroundResource(R.drawable.tabs_item_left_bg);
                    scheduleTab.setBackgroundResource(R.drawable.tabs_item_selected_right_bg);
                    appointmentsListRender(token, date, groupGuid, viewElements[viewFlipper.getIndex()].lv);
                    viewElements[viewFlipper.getIndex()].emptyView.setText(R.string.no_availability);
                } else if (viewId == leftArrow.getId()) {
                    viewFlipper.showPrevious();
                } else {
                    viewFlipper.showNext();
                }
            }
        };

        addButton.setOnClickListener(onClickListener);
        availabilityTab.setOnClickListener(onClickListener);
        scheduleTab.setOnClickListener(onClickListener);
        leftArrow.setOnClickListener(onClickListener);
        rightArrow.setOnClickListener(onClickListener);

        myGroupDropdownAdapter = new MyGroupDropdownAdapter<MyGroup>(getActivity(), R.layout.groups_spinner_dropdown_item);

        //第三步：为适配器设置下拉列表下拉时的菜单样式。
        myGroupDropdownAdapter.setDropDownViewResource(R.layout.groups_spinner_dropdown_item);

        //第四步：将适配器添加到下拉列表上
        groupsSpinner.setAdapter(myGroupDropdownAdapter);

        groupsSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @SuppressWarnings("unchecked")
            public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) {
                                /* 将mySpinner 显示*/
                arg0.setVisibility(View.VISIBLE);
                groupGuid = groups.get(arg2).getGroupGuid();
                renderViewFlipper(viewFlipper.getIndex(), date);

            }

            @SuppressWarnings("unchecked")
            public void onNothingSelected(AdapterView arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });



    }


    private void loadGroups() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                groups = ServerAccessHelper.loadMyGroups(token.getToken());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        myGroupDropdownAdapter.notifyDataSetChanged();
                   }
                });

            }
        }).start();
    }

    private class MyGroupDropdownAdapter<MyGroup> extends ArrayAdapter {
        private Context mainContext;

        public MyGroupDropdownAdapter(Context context, int resource) {
            super(context, resource, groups);
            mainContext = context;

        }

        @Override
        public void notifyDataSetChanged() {
            int count = getCount();
            if (count == 0) {
                addAll(groups);
            } else {
                super.notifyDataSetChanged();
            }
            groupsSpinner.setSelection(1);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = super.getView(position, convertView, parent);

            setTextStyle(view);

            return view;
        }

        private void setTextStyle(View convertView) {
            CustomApplication application = (CustomApplication) mainContext.getApplicationContext();

            if (convertView instanceof TextView) {
                TextView currentTextView = (TextView) convertView;
                currentTextView.setTypeface(application.getHuaWenHuPo());
            }
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {

            View dropDownView = super.getDropDownView(position, convertView, parent);

            setTextStyle(dropDownView);

            return dropDownView;
        }
    }


    CustomViewFlipper.MyViewFlipperLoadData loadViewData = new CustomViewFlipper.MyViewFlipperLoadData() {
        public void loadData(final int index) {

            int currentDataIndex = viewFlipper.getCurrentDataIndex();


            final String currentDate = TimeUtils.getDate(currentDataIndex - currentIndex, 1, true);

            timeView.setText(TimeUtils.dateLabel(currentDate));

            date = currentDate;

            renderViewFlipper(index, currentDate);


        }

        @Override
        public boolean canLoadData() {
            int currentDataIndex = viewFlipper.getCurrentDataIndex();
            return !(tab.equals("availability") && currentDataIndex <= currentIndex);
        }
    };

    private void renderViewFlipper(int index, String currentDate) {
        if ("availability".equals(tab)) {
            viewElements[index].emptyView.setText(R.string.no_appointment);
            availabilityListRender(token, currentDate, groupGuid, viewElements[index].lv);
        } else {
            viewElements[index].emptyView.setText(R.string.no_availability);
            appointmentsListRender(token, currentDate, groupGuid, viewElements[index].lv);
        }
    }


    @Override
    public int getViewId() {
        return R.layout.my_appointments;
    }

    @Override
    public int getSourceId() {
        return R.id.my_appointments;
    }

    @Override
    public boolean isParent() {
        return true;
    }

    @Override
    public void updateUI() {

        users.clear();
        if (token != null) {
            loadGroups();
        }

    }


    private void deleteAppointment(final Appointment appointment) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                JSONObject profileJsonObj = new JSONObject();

                try {
                    profileJsonObj.put("guid", appointment.getGuid());
                    StringEntity paramEntity = new StringEntity(profileJsonObj.toString(), Constant.CHARSET_UTF8);
                    String result = ServerAccessHelper.queryStringForDelete(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT), token.getToken(), paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                appointments.remove(appointment);
                                appointmentsAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }


            }
        }).start();
    }


    private void reject(final Appointment appointment) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject paramJson = new JSONObject();
                try {
                    paramJson.put("guid", appointment.getGuid());
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                    String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT_INVITATION_REJECT), token.getToken(), paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                appointments.remove(appointment);
                                appointmentsAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void availabilityListRender(final UserToken token, final String date, final String groupGuid, final ListView listView) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                json = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.AVAILABILITY_SEARCH) + "?date=" + date + "&groupGuid=" + groupGuid, token.getToken());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!Constant.RESPONSE_BADLY.equals(json)) {
                            try {
                                availabilities.clear();
                                final JSONArray requestsArray = new JSONArray(json);
                                final int length = requestsArray.length();
                                for (int i = 0; i < length; i++) {
                                    JSONObject requestObj = requestsArray.getJSONObject(i);
                                    JSONObject user = requestObj.getJSONObject("user");
                                    String userGuid = user.getString("guid");
                                    String userName = user.getString("name");
                                    String userAvatar = user.getString("avatar");
                                    JSONObject date = requestObj.getJSONObject("date");
                                    String dateStr = date.getString("date");
                                    JSONArray parts = date.getJSONArray("parts");
                                    List<Period> periods = new ArrayList<Period>();
                                    for (int j = 0; j < parts.length(); j++) {
                                        String period = (String) parts.get(j);
                                        periods.add(Period.valueOf(period));
                                    }
                                    availabilities.add(new Availability(userGuid, userName, userAvatar, dateStr, periods));
                                }
                                availabilitiesRequestAdapter = new AvailabilitiesRequestAdapter(getActivity(), R.layout.availability_list_item);
                                listView.setAdapter(availabilitiesRequestAdapter);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
        }).start();
    }


    private class AvailabilitiesRequestAdapter extends BaseAdapter {

        private int resource;//数据绑定在哪个资源界面上
        private LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象
        private AvailabilityItemViewCache viewCache;

        private AvailabilitiesRequestAdapter(Context context, int resource) {
            this.resource = resource;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return availabilities.size();
        }

        @Override
        public Object getItem(int position) {
            return availabilities.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            HuaWenHuPoTextView usernameView, periodsView;
            ImageButton appointBtn;
            ImageView appointSelectedView, avatarView;
            if (convertView == null) {//第一次渲染
                convertView = inflater.inflate(resource, null);
                usernameView = (HuaWenHuPoTextView) convertView.findViewById(R.id.username);
                periodsView = (HuaWenHuPoTextView) convertView.findViewById(R.id.periods);
                appointBtn = (ImageButton) convertView.findViewById(R.id.appoint_button);
                appointSelectedView = (ImageView) convertView.findViewById(R.id.appoint_selected);
                avatarView = (ImageView) convertView.findViewById(R.id.user_photo);
                viewCache = new AvailabilityItemViewCache();
                viewCache.usernameView = usernameView;
                viewCache.periodsView = periodsView;
                viewCache.appointButton = appointBtn;
                viewCache.appointSelectedView = appointSelectedView;
                viewCache.avatarView = avatarView;
                convertView.setTag(viewCache);
            } else {
                viewCache = (AvailabilityItemViewCache) convertView.getTag();
                appointSelectedView = viewCache.appointSelectedView;
                appointBtn = viewCache.appointButton;
            }
            Availability availability = availabilities.get(position);
            viewCache.usernameView.setText(availability.getUserName());
            viewCache.periodsView.setText(availability.showLabel());

            viewCache.avatarView.setTag(availability.userGuid);
            loadUserImage(availability.userGuid, viewCache.avatarView);
            appointBtn.setOnClickListener(new ButtonListener(appointSelectedView, position));

            return convertView;
        }

        private class ButtonListener implements View.OnClickListener {
            ImageView appointSelectedView;
            int position;

            private ButtonListener(ImageView appointSelectedView, int position) {
                this.appointSelectedView = appointSelectedView;
                this.position = position;
            }

            @Override
            public void onClick(View v) {
                int visibility = appointSelectedView.getVisibility();
                final int newVisibility;
                Availability availability = availabilities.get(position);
                if (View.VISIBLE == visibility) {
                    newVisibility = View.GONE;
                    Iterator<User> userListIterator = users.iterator();
                    while (userListIterator.hasNext()) {
                        User user = userListIterator.next();
                        if (user.getGuid().equals(availability.userGuid)) userListIterator.remove();
                    }
                } else {
                    newVisibility = View.VISIBLE;
                    User user = new User(availability.userGuid, availability.userName);
                    if (!users.contains(user)) {
                        users.add(user);
                    }
                }

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        appointSelectedView.setVisibility(newVisibility);

                    }
                });


            }

        }

        private class AvailabilityItemViewCache {
            private HuaWenHuPoTextView usernameView;
            private HuaWenHuPoTextView periodsView;
            private ImageButton appointButton;
            private ImageView appointSelectedView;
            private ImageView avatarView;
        }
    }


    private class Availability {
        private String userGuid;

        private String userName;

        private String userAvatar;

        private String date;

        private List<Period> periods;

        private Availability(String userGuid, String userName, String userAvatar, String date, List<Period> periods) {
            this.userGuid = userGuid;
            this.userName = userName;
            this.userAvatar = userAvatar;
            this.date = date;
            this.periods = periods;
        }


        public String getUserName() {
            return userName;
        }


        public String showLabel() {
            Collections.sort(periods, new Comparator<Period>() {
                @Override
                public int compare(Period period, Period period2) {
                    return period.getSort().compareTo(period2.getSort());
                }
            });
            String label = date;
            for (Period period : periods) {
                String prefix;
                switch (period) {
                    case MORNING:
                        prefix = "，上午";
                        break;
                    case AFTERNOON:
                        prefix = "，下午";
                        break;
                    default:
                        prefix = "，晚上";
                        break;

                }
                label = label + prefix;
            }
            return label;
        }

        public String getDate() {
            return date;
        }
    }


    private void appointmentsListRender(final UserToken token, final String date, final String groupGuid, final ListView view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                json = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENTS) + "?date=" + date + "&groupGuid=" + groupGuid, token.getToken());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!Constant.RESPONSE_BADLY.equals(json)) {
                            try {
                                //remove old data
                                users.clear();
                                appointments.clear();
                                final JSONArray requestsArray = new JSONArray(json);
                                final int length = requestsArray.length();
                                for (int i = 0; i < length; i++) {
                                    JSONObject requestObj = requestsArray.getJSONObject(i);
                                    String guid = requestObj.getString("guid");
                                    JSONObject creatorObj = requestObj.getJSONObject("creator");
                                    String creatorGuid = creatorObj.getString("guid");
                                    String creatorName = creatorObj.getString("name");
                                    String creatorAvatar = creatorObj.getString("avatar");
                                    String location = requestObj.getString("location");
                                    int participantsAmount = requestObj.getInt("participantsAmount");
                                    int currentParticipantsAmount = requestObj.getInt("currentParticipantsAmount");
                                    boolean invitee = requestObj.getBoolean("invitee");
                                    int requestsAmount = requestObj.getInt("requestsAmount");
                                    appointments.add(new Appointment(guid, creatorGuid, creatorName, creatorAvatar, location, participantsAmount, currentParticipantsAmount, invitee, requestsAmount));
                                }
                                appointmentsAdapter = new AppointmentsAdapter(getActivity(), R.layout.appointment_item);
                                view.setAdapter(appointmentsAdapter);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
        }).start();
    }

    private void accept(final Appointment appointment) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject paramJson = new JSONObject();
                try {
                    paramJson.put("guid", appointment.getGuid());
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                    String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT_INVITATION_ACCEPT), token.getToken(), paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                appointment.acceptInvitation();
                                appointmentsAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    protected class AppointmentsAdapter extends BaseAdapter {
        private int resource;//数据绑定在哪个资源界面上
        private LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象
        private AppointmentItemViewCache viewCache;

        private AppointmentsAdapter(Context context, int resource) {
            this.resource = resource;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return appointments.size();
        }

        @Override
        public Object getItem(int position) {
            return appointments.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HuaWenHuPoTextView creatorNameView, locationView, percentView, requestNumberView;
            ImageView roundPointView, creatorAvatarView;
            final Appointment appointment = appointments.get(position);


            if (convertView == null) {//第一次渲染
                convertView = inflater.inflate(resource, null);
                creatorNameView = (HuaWenHuPoTextView) convertView.findViewById(R.id.creatorName);
                locationView = (HuaWenHuPoTextView) convertView.findViewById(R.id.location);
                percentView = (HuaWenHuPoTextView) convertView.findViewById(R.id.percent);
                roundPointView = (ImageView) convertView.findViewById(R.id.round);
                requestNumberView = (HuaWenHuPoTextView) convertView.findViewById(R.id.request_amount);
                creatorAvatarView = (ImageView) convertView.findViewById(R.id.user_photo);
                if (appointment.isOwner() && appointment.requestsAmount > 0) {
                    requestNumberView.setText(appointment.getRequestsAmount() + "");
                    requestNumberView.setVisibility(View.VISIBLE);
                }


                boolean hasInvitation = !appointment.isOwner() && appointment.isInvitee();
                if (hasInvitation) {
                    roundPointView.setVisibility(View.VISIBLE);
                }

                viewCache = new AppointmentItemViewCache();
                viewCache.creatorNameView = creatorNameView;
                viewCache.locationView = locationView;
                viewCache.percentView = percentView;
                viewCache.roundPointView = roundPointView;
                viewCache.requestNumberView = requestNumberView;
                viewCache.creatorAvatarView = creatorAvatarView;
                convertView.setTag(viewCache);
            } else {
                viewCache = (AppointmentItemViewCache) convertView.getTag();
            }

            viewCache.creatorNameView.setText(appointment.getCreatorNameLabel());
            viewCache.locationView.setText(appointment.getLocation());
            viewCache.percentView.setText(appointment.getParticipantsPercent());

            viewCache.creatorAvatarView.setTag(appointment.creatorGuid);
            loadUserImage(appointment.creatorGuid, viewCache.creatorAvatarView);
            final boolean hasInvitation = !appointment.isOwner() && appointment.isInvitee();

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final boolean owner = appointment.isOwner();

                    if (hasInvitation) {
                        goFragment(R.id.my_appointments, JoinAppointmentFragment.TAG, JoinAppointmentFragment.class, null, false);

                    } else {
                        goFragment(R.id.my_appointments, owner ? MyAppointmentFragment.TAG : JoinAppointmentFragment.TAG, owner ? MyAppointmentFragment.class : JoinAppointmentFragment.class, null, false);

                    }

                }
            });
            convertView.setOnLongClickListener(new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View view) {


                    Session session = Session.newSession();
                    session.put("appointmentGuid", appointment.getGuid());

                    if (hasInvitation) {
                        showPopupMenu(view, R.menu.details_accept_reject_menu, new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem menuItem) {
                                int menuItemId = menuItem.getItemId();
                                if (menuItemId == R.id.accept_menu) {
                                    accept(appointment);
                                } else {
                                    reject(appointment);
                                }
                                return true;
                            }
                        });
                    } else {
                        showPopupMenu(view, R.menu.details_delete_menu, new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem menuItem) {
                                deleteAppointment(appointment);
                                return true;
                            }
                        });

                    }


                    return true;
                }
            });
            return convertView;
        }

        private class AppointmentItemViewCache {
            HuaWenHuPoTextView creatorNameView;
            HuaWenHuPoTextView locationView;
            HuaWenHuPoTextView percentView;
            HuaWenHuPoTextView requestNumberView;
            ImageView roundPointView;
            ImageView creatorAvatarView;
        }


    }


    private class Appointment {

        private String guid;

        private String creatorGuid;

        private String creatorName;

        private String creatorAvatar;

        private String location;

        private int participantsAmount;

        private int currentParticipantsAmount;

        private boolean invitee;

        private int requestsAmount;

        public Appointment(String guid, String creatorGuid, String creatorName, String creatorAvatar, String location, int participantsAmount, int currentParticipantsAmount, boolean invitee, int requestsAmount) {
            this.guid = guid;
            this.creatorGuid = creatorGuid;
            this.creatorName = creatorName;
            this.creatorAvatar = creatorAvatar;
            this.location = location;
            this.participantsAmount = participantsAmount;
            this.currentParticipantsAmount = currentParticipantsAmount;
            this.invitee = invitee;
            this.requestsAmount = requestsAmount;
        }


        public String getGuid() {
            return guid;
        }

        public String getCreatorNameLabel() {
            if (isOwner()) {
                return Constant.ME;
            }
            return creatorName;
        }

        public boolean isOwner() {
            return token.getGuid().equals(creatorGuid);
        }


        public String getLocation() {
            return location;
        }

        public String getDate() {
            return date;
        }

        public String getParticipantsPercent() {
            return currentParticipantsAmount + "/" + participantsAmount;
        }

        public void acceptInvitation() {
            currentParticipantsAmount++;
            invitee = false;
        }

        public boolean isInvitee() {
            return invitee;
        }

        public int getRequestsAmount() {
            return requestsAmount;
        }
    }

    public class ViewElement {


        ListView lv;

        HuaWenHuPoTextView emptyView;


        public ViewElement(View view, int index) {


            lv = (ListView) view.findViewById(R.id.list_in_flipper);

            emptyView = (HuaWenHuPoTextView) view.findViewById(R.id.empty_text);

            emptyView.setText(R.string.no_appointment);

            lv.setEmptyView(emptyView);

            timeView.setText(TimeUtils.dateLabel(date));

            if (token != null && index == 0) {
                availabilityListRender(token, date, null, lv);
            }

            // ScrollView滑动时触发切换事件
            viewFlipper.setChildTouchListener(this.lv);
        }
    }

}
